import { AdminModel } from '~/server/models/admin.model';

// 管理员用户登录
export default defineEventHandler(async (event): Promise<any> => {
	const { username, password } = await readBody(event);

	if (!username || !password) {
		return { code: 0, message: '用户名或密码不能为空' };
	}

	try {
		// 验证用户名和密码
		const findUser = await AdminModel.findOne({ username, password: sha256(md5(password)) });

		if (!findUser) {
			return { code: 0, message: '用户名或密码错误' };
		}

		// 生成 Token
		const token: string | undefined = await signToken({ id: findUser._id }, 30);

		// 返回 Cookie Token
		setCookie(event, 'token', `Bearer ${token}` as string, {
			path: '/',
			httpOnly: true,
			secure: process.env.NODE_ENV === 'production',
			maxAge: 30 * 24 * 60 * 60 * 1000,
		});
		return { code: 1, message: '登录成功' };
	} catch (error: any) {
		return { code: 0, message: error.message };
	}
});
